package com.telecom.util;

import com.telecom.entity.Student;
import lombok.extern.slf4j.Slf4j;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j(topic = "c.DBUtil")
public class DBUtil {
    public static Connection getConnection(DbProfile profile) {
        try {
            //加载驱动
            Class.forName(profile.getDriver());
            log.debug("load jdbc driver success!");
            //获取连接
            return DriverManager.getConnection(profile.getUrl(), profile.getUsername(), profile.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public <E> List<E> selectList(Connection connection,Mapper mapper){
        String sql=mapper.getSqlStatement();//要执行的SQL语句 select * from student
        String className=mapper.getClassName(); //查询的结果映射的实体类名称com.telecom.entity.Student
        try {
            Class<?> aClass = Class.forName(className);
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //执行sql，得到结果集
            ResultSet resultSet = preparedStatement.executeQuery();
            List<E> list = new ArrayList<>();
            while (resultSet.next()){
                E obj = (E) aClass.getConstructor().newInstance();
                //结果集元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                //统计查询的结果集有多少列
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    //获取到列名和值
                    String columnName = metaData.getColumnName(i);
                    Object value = resultSet.getObject(i);
                    PropertyDescriptor  propertyDescriptor = new PropertyDescriptor(columnName, aClass);
                    //获取写入的方法  setId  setName  setAge
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    //调用方法完成赋值
                    writeMethod.invoke(obj,value);
                }
                list.add(obj);
            }
            return list;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
